import { ColumnDef } from '@tanstack/react-table'
import { MoreHorizontal } from 'lucide-react'

import { Button } from '@renderer/components/ui/button'
import { Checkbox } from '@renderer/components/ui/checkbox'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger
} from '@renderer/components/ui/dropdown-menu'
import type { ModelChat } from '@shared/types/entity'
import { DrawerTrigger } from '@renderer/components/ui/drawer'
import useModelChatStore from '@renderer/store/model-chat'
import { useShallow } from 'zustand/react/shallow'

const deleteByMark = async (mark: string) => {
  await window.api.modelChat.deleteByMark(mark)
}

export const getColumns = (): ColumnDef<ModelChat>[] => {
  const { getData, editFrom } = useModelChatStore(
    useShallow((state) => ({
      getData: state.getData,
      editFrom: state.editForm
    }))
  )
  return [
    {
      id: 'select',
      header: ({ table }) => (
        <Checkbox
          checked={
            table.getIsAllPageRowsSelected() ||
            (table.getIsSomePageRowsSelected() && 'indeterminate')
          }
          onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
          aria-label="Select all"
          className="translate-y-[2px]"
        />
      ),
      cell: ({ row }) => (
        <Checkbox
          checked={row.getIsSelected()}
          onCheckedChange={(value) => row.toggleSelected(!!value)}
          aria-label="Select row"
          className="translate-y-[2px]"
        />
      ),
      enableSorting: false,
      enableHiding: false
    },
    {
      accessorKey: 'mark',
      header: '标识',
      enableSorting: false,
      enableHiding: false
    },
    {
      accessorKey: 'name',
      header: '名称'
    },
    {
      accessorKey: 'url',
      header: '访问API'
    },
    {
      accessorKey: 'model',
      header: 'model'
    },
    {
      id: 'actions',
      header: '操作',
      cell: ({ row }) => {
        const payment = row.original
        return (
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button variant="ghost" className="h-8 w-8 p-0">
                <span className="sr-only">Open menu</span>
                <MoreHorizontal className="h-4 w-4" />
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
              <DrawerTrigger asChild>
                <DropdownMenuItem onClick={() => editFrom('edit', payment)}>编辑</DropdownMenuItem>
              </DrawerTrigger>
              <DropdownMenuSeparator />
              <DropdownMenuItem
                onClick={() => {
                  deleteByMark(payment.mark)
                  getData()
                }}
              >
                删除
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        )
      }
    }
  ]
}
